//
//  STTools_VideoLoadManger.m
//  togetherPlay
//
//  Created by Mac on 2019/12/21.
//  Copyright © 2018  STTools_owenr. All rights reserved.
//

#import "STTools_VideoLoadManger.h"
#import "NSString+STTools_MD5.h"
#import "TZImagePickerController.h"
#define video_front_image @"video_front_image"
@interface STTools_VideoLoadManger()
@end
@implementation STTools_VideoLoadManger
+ (STTools_VideoLoadManger*)manger{
    static STTools_VideoLoadManger * manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = STTools_VideoLoadManger.new;
    });
    return manger;
}
- (void)loadVideoCacheWithUrl:(NSString *)url compelet:(void (^)(UIImage *, NSString *))complete{
    NSString *cachepath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString * path = [NSString stringWithFormat:@"%@/%@",cachepath,video_front_image];
    NSString * dealDomin = [url componentsSeparatedByString:@"."].firstObject;
    dealDomin = [url stoneobs_fun_st_md532BitLower];
    
    NSString * imagePath = [NSString stringWithFormat:@"%@/%@.png",path,dealDomin];
    NSFileManager* fileManager= [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:imagePath isDirectory:&isDir];
    if (existed) {
        UIImage * image = [[UIImage alloc] initWithContentsOfFile:imagePath];
        if (complete) {
            complete(image,imagePath);
        }
    }else{
        //
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //取第一针 图片
            UIImage * image = [self imageWithVideoUrl:url];
            [self saveImage:image url:url];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete && image) {
                    complete(image,imagePath);
                }
            });
        });
    }
}
- (void)createFolder{
    NSString *cachepath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString * path = [NSString stringWithFormat:@"%@/%@",cachepath,video_front_image];
    //创建一个 目录
    NSString * realFatherPath = [NSString stringWithFormat:@"%@/%@",cachepath,video_front_image];
    BOOL ducisDir = YES;
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    NSFileManager* fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:realFatherPath isDirectory:&ducisDir];
    if(!existed){
        [fileManager createDirectoryAtPath:realFatherPath withIntermediateDirectories:YES attributes:nil error:nil];
        DDLogInfo(@"创建目录成功:%@",realFatherPath);
        
    }else{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            DDLogInfo(@"该目录已经存在:%@",realFatherPath);
        });
        
    }
}
- (UIImage*)imageWithVideoUrl:(NSString*)videoUrl{
    //获取第一针 图片
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:videoUrl] options:opts];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(UISCREEN_WIDTH , UISCREEN_HEIGHT );
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
    {
        return [UIImage imageWithCGImage:img];
    }
    return nil;
}
- (void)saveImage:(UIImage*)image url:(NSString*)url{
    NSString *cachepath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString * path = [NSString stringWithFormat:@"%@/%@",cachepath,video_front_image];
    //创建一个 目录
    NSString * realFatherPath = [NSString stringWithFormat:@"%@/%@",cachepath,video_front_image];
    BOOL ducisDir = YES;
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    NSFileManager* fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:realFatherPath isDirectory:&ducisDir];
    if(!existed){
        [fileManager createDirectoryAtPath:realFatherPath withIntermediateDirectories:YES attributes:nil error:nil];
        DDLogInfo(@"创建目录成功:%@",realFatherPath);

    }else{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            DDLogInfo(@"该目录已经存在:%@",realFatherPath);
        });
        
    }
    

    
    NSString * dealDomin = [url componentsSeparatedByString:@"."].firstObject;
    dealDomin = [url stoneobs_fun_st_md532BitLower];
    NSString * imagePath = [NSString stringWithFormat:@"%@/%@.png",path,dealDomin];
    

    BOOL isDir = NO;
    BOOL imgexisted = [fileManager fileExistsAtPath:imagePath isDirectory:&isDir];
    if (imgexisted) {
        DDLogInfo(@"该视屏封面地址已经缓存:%@",imagePath);
        return;
    }
    //存入 沙盒
    NSData *imageData = UIImagePNGRepresentation(image);
   BOOL success =  [imageData writeToFile:imagePath atomically:NO];
    if (success) {
        DDLogInfo(@"写入文件成功:%@",imagePath);
    }else{
        DDLogInfo(@"缓存失败:%@",imagePath);
    }
    
}

@end
